package sw.controller;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import sw.entity.Project;

@Controller
@RequestMapping("/weak")
public class WealnessController extends BaseController {

	public WealnessController(ResourceLoader resourceLoader) {
		super(resourceLoader);
	}
	
	@RequestMapping("/exportExcel")
    public void exportImportantExcel(HttpServletRequest request, HttpServletResponse response, Integer projectId) throws Exception {
		Workbook workbook = weaknessService.ExportThreat(projectId);
		Project pro = projectService.findById(projectId);
		if(null == pro) return;
		String filenames = pro.getName()+"脆弱性识别赋值表.xlsx";
        try {
            response.reset();
            // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filenames.replaceAll(" ", "").getBytes("utf-8"), "iso8859-1"));
            response.setContentType("application/octet-stream");
            response.flushBuffer();  
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	
	@RequestMapping(value = "/importExcel")//威胁识别表导入
	@ResponseBody
	public String importExcel1(@PathVariable MultipartFile file,Integer projectId,HttpServletRequest request) {
		if (!file.isEmpty()) {
			String fileName = file.getOriginalFilename();// 获取文件名
			String suffixName = fileName.substring(fileName.lastIndexOf("."));//获取文件的后缀名
		    fileName = UUID.randomUUID() + suffixName;
			try {
				Files.copy(file.getInputStream(),Paths.get(UPLOADPATH, fileName));//getOriginalFilename得到上传时的文件名
				String str = Paths.get(UPLOADPATH, fileName).toString();
				weaknessService.importExcel(str, projectId);//保存数据
			} catch (Exception e) {
				e.printStackTrace();
				return "上传失败";
			}
			return "上传成功";
		}
		return "文件为空";
	}

}
